//
//  AmountFormatter.m
//  Peso Guide
//
//  Created by macbook on 2025/6/7.
//

#import "AmountFormatter.h"

@implementation AmountFormatter

+ (NSString *)formatAmount:(id)amount {
    return [self formatAmount:amount withDecimalPlaces:0];
}

+ (NSString *)formatAmount:(id)amount withDecimalPlaces:(NSInteger)decimalPlaces {
    // 确保输入有效
    if (!amount) return @"0.00";
    
    NSNumber *number = nil;
    
    if ([amount isKindOfClass:[NSString class]]) {
        // 处理字符串输入
        NSString *stringAmount = (NSString *)amount;
        
        // 去除可能存在的格式化和货币符号
        NSString *cleanString = [stringAmount stringByReplacingOccurrencesOfString:@"," withString:@""];
        cleanString = [cleanString stringByTrimmingCharactersInSet:[NSCharacterSet symbolCharacterSet]];
        
        // 转换为数字
        NSNumberFormatter *cleanFormatter = [[NSNumberFormatter alloc] init];
        cleanFormatter.numberStyle = NSNumberFormatterDecimalStyle;
        number = [cleanFormatter numberFromString:cleanString];
        
        if (!number) {
            // 尝试直接转换
            number = @([cleanString doubleValue]);
        }
    } else if ([amount isKindOfClass:[NSNumber class]]) {
        number = (NSNumber *)amount;
    } else {
        return @"0.00";
    }
    
    // 处理无效数字
    if (!number || [number isEqual:[NSNull null]] || isnan([number doubleValue])) {
        return @"0.00";
    }
    
    // 设置格式化器
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    formatter.minimumFractionDigits = decimalPlaces;
    formatter.maximumFractionDigits = decimalPlaces;
    formatter.roundingMode = NSNumberFormatterRoundHalfUp;
    
    return [formatter stringFromNumber:number];
}

+ (NSString *)formatAmount:(id)amount withCurrencySymbol:(NSString *)symbol {
    NSString *formatted = [self formatAmount:amount];
    return [NSString stringWithFormat:@"%@%@", symbol ?: @"", formatted];
}

+ (NSString *)removeFormatting:(NSString *)formattedString {
    // 去除千分位逗号和货币符号
    NSString *cleanString = [formattedString stringByReplacingOccurrencesOfString:@"," withString:@""];
    
    // 创建字符集去除所有非数字字符（保留小数点和负号）
    NSCharacterSet *allowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789.-"] invertedSet];
    cleanString = [[cleanString componentsSeparatedByCharactersInSet:allowedChars] componentsJoinedByString:@""];
    
    // 处理多个小数点的情况
    NSArray *components = [cleanString componentsSeparatedByString:@"."];
    if (components.count > 2) {
        cleanString = [NSString stringWithFormat:@"%@.%@",
                       components.firstObject,
                       [[components subarrayWithRange:NSMakeRange(1, components.count-1)] componentsJoinedByString:@""]];
    }
    
    return cleanString;
}

@end
